<script>
import {ref, nextTick, watch} from 'vue';
import CustomButton from '@/components/button/index.vue';
import {ElMessage} from 'element-plus';
import {Chat} from "@/api/api.js";
import {TokenService} from "@/stores/userStore.js";

export default {
  name: 'ChatBox',
  components: {
    CustomButton
  },
  props: {
    initialMessages: {
      type: Array,
      default: () => []
    },
    deleteChat: {
      type: Function,
      default: () => {
        console.log('清空成功');
      }
    },
    exportChatRecord: {
      type: Function,
      default: () => {
        console.log('导出成功');
      },
    },
    currentChatId: {
      type: Number,
      default: 0,
    },
  },
  setup(props) {
    console.log(props.initialMessages)
    const question = ref('');
    const messages = ref(props.initialMessages);
    const endOfMessages = ref(null);

    // 监听 initialMessages 的变化，动态更新 messages
    watch(() => props.initialMessages, (newMessages) => {
      messages.value = newMessages;
    });

    const sendMessage = () => {
      if (question.value.trim()) {
        messages.value.push({text: `Q: ${question.value}`, type: 'question'});
        // 模拟回答
        let answer = "回答有问题，请重新问"
        const user_id =TokenService.getCurrentUserId()
        Chat(user_id,props.currentChatId, question.value.trim()).then(res => {
          if (!res.success) {
            console.log(res.message)
          }else{
            // 模拟流式输出
            let responseText = res.response;
            let currentText = '';
            const interval = 50; // 每50毫秒更新一次
            messages.value.push({text:' Q:', type: 'answer'});
            const intervalId = setInterval(() => {
              if (currentText.length < responseText.length) {
                currentText += responseText[currentText.length];
                messages.value[messages.value.length - 1] = { text: `A: "${currentText}"`, type: 'answer' };
                scrollToBottom();
              } else {
                clearInterval(intervalId);
                question.value = '';
              }
            }, interval);
          }
        }).catch(err => {
          console.log(err)
        })
      }
    };

    const scrollToBottom = () => {
      nextTick(() => {
        endOfMessages.value.scrollIntoView({behavior: 'smooth'});
      });
    };

    return {
      question,
      messages,
      endOfMessages,
      sendMessage,
      scrollToBottom
    };
  }
}
;
</script>

<template>
  <div class="chatBox">
    <!-- 顶部 -->
    <div class="top-container">
      <div class="content">
        <el-icon>
          <ChatLineSquare/>
        </el-icon>
        <i>{{ $t('chatBox.topContainer.content.title') }}</i>
      </div>
      <div class="btn">
        <CustomButton :label="$t('chatBox.topContainer.buttons.clearConversation')"
                      @click="$props.deleteChat"></CustomButton>
        <CustomButton :label="$t('chatBox.topContainer.buttons.exportConversation')"
                      @click="$props.exportChatRecord"></CustomButton>
      </div>
    </div>
    <!-- 对话框 -->
    <div class="answer" ref="answerBox">
      <div v-for="(msg, index) in messages" :key="index" class="message" :class="msg.type">
        <div class="bubble">{{ msg.text }}</div>
      </div>
      <!-- 用于滚动到底部的占位元素 -->
      <div ref="endOfMessages"></div>
    </div>
    <!-- 提问 -->
    <div class="ask">
      <el-input
        v-model="question"
        :placeholder="$t('chatBox.ask.placeholder')"
        class="input"
      />
      <CustomButton :label="$t('chatBox.sendButton')" @click="sendMessage"></CustomButton>
    </div>
  </div>
</template>

<style scoped>
@import "/src/css/base.css";
@import "./index.css";
</style>
